#include <TimerOne.h>
#include <Arduino.h>
//#include "datatypes.h"
#include "igniter.h"

const int pin_IGTp = 12;
const int pin_IGTn = 11;

#define pin_checkp A0
#define pin_checkn A1

const uint16_t comm_range[2] = {400,600};
const uint16_t diff_range[2] = {2,23};

bool IGTA,IGTB,tick;
uint16_t eta;
#define IGT_LIMIT	1000

static void IGT_service(void);

void IGT_init(void)
{
  pinMode(pin_IGTp,OUTPUT);
  pinMode(pin_IGTn,OUTPUT);
  digitalWrite(pin_IGTp,LOW);
  digitalWrite(pin_IGTn,LOW);
  IGTA = false;
  IGTB = false;
  Timer1.initialize(100);
  Timer1.attachInterrupt(IGT_service);
  
  //Serial.println("IGT:init");
}

void IGT_enable(void)
{
  Timer1.stop();
  IGTA = true;
  IGTB = true;
  eta = IGT_LIMIT;
  Timer1.start();
  
  //Serial.println("IGT:enable");
}

void IGT_disable(void)
{
  Timer1.stop();
  digitalWrite(pin_IGTp,LOW);
  digitalWrite(pin_IGTn,LOW);
  IGTA = false;
  IGTB = false;
  
  //Serial.println("IGT:disable");
}

bool IGT_check(void)
{
  uint32_t vh,vl;
  uint16_t diff,comm;
  uint16_t i;

  for(i=0;i<256;i++)
  {
    vh = analogRead(pin_checkp);
    vl = analogRead(pin_checkn);
  }
  vh /= 256;
  vl /= 256;

  diff = (vh - vl);
  comm = (vh + vl)/2;

  Serial.print("#IGNITER,CHECK,C=");
  Serial.print(comm);
  Serial.print(",D=");
  Serial.print(diff);
  Serial.print("\r\n");
  
  if(diff > diff_range[0]
    &&diff < diff_range[1]
    &&comm > comm_range[0]
    &&comm < comm_range[1]
    )
  {
    //Serial.println("IGT:check ok");
    return true;
  }
  
  //Serial.println("IGT:check err");
  return false;
}

void IGT_service(void)
{
  if(IGTA && IGTB)
  {
    if(tick)
    {
      tick = false;
      digitalWrite(pin_IGTp,HIGH);
      digitalWrite(pin_IGTn,LOW);
    }
    else
    {
      tick = true;
      digitalWrite(pin_IGTn,HIGH);
      digitalWrite(pin_IGTp,LOW);
    }
    eta--;
    if(eta == 0 || eta > IGT_LIMIT)
      IGT_disable();
  }
}


